const app = getApp()
import { calendar, checkin } from '../../../../api/mine/checkin'
import { setting } from '../../../../api/mine/points'
import { getInfo, setInfo } from '../../../../utils/user'

Page({
  data: {
    theme: '',
    back: true,
    title: '积分中心',
    login: false,
    loading: false,
    submitLoading: false,
    calendar: [],
    points: 0,
    active: 0,
    today: 0,
    days: 0,
    info: null,
    rule: ''
  },
  onLoad (options) {
    this.setData({
      theme: app.global.theme,
      info: getInfo()
    })
    setting().then(res => {
      this.setData({ rule: res.data.content })
    })
    if (app.login()) {
      this.getCalendar()
    }
  },
  onShow () {},
  onPullDownRefresh () { /* 监听用户下拉动作*/ },
  onReachBottom () { /* 页面上拉触底事件的处理函数*/ },

  // ===================method================//

  getCalendar () {
    this.setData({ loading: true })
    calendar().then(res => {
      this.setData({
        points: res.data.points,
        active: res.data.active,
        today: res.data.today,
        days: res.data.days,
        calendar: res.data.calendar
      })
    })
      .finally(() => {
        this.setData({ loading: false })
      })
  },

  checkin () {
    if (app.login()) {
      this.setData({ submitLoading: true })
      checkin().then(res => {
        this.setData({
          points: this.data.points + res.data,
          active: this.data.active + 1,
          days: this.data.days + 1,
          today: 1
        })
      })
        .finally(() => {
          this.setData({ submitLoading: false })
        })
    } else {
      this.setData({ login: true })
    }
  },

  login () {
    if (!app.login()) {
      this.setData({
        login: true
      })
    }
  },

  redirect (event) {
    if (app.login()) {
      app.redirect(event.currentTarget.dataset.url)
    } else {
      this.setData({
        login: true
      })
    }
  }
})